package com.sjw.login.util;

import cn.hutool.core.text.StrJoiner;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Random;

public class PasswordGenerationUtil {

    private static final String PRIVATE_KEY = "SHA-256";
    private static final int SALT_LENGTH = 16;

    // 使用sha256 + 随机盐
    /**
     * 生成随机盐
     */
    private static String generateSalt(){
        Random random = new SecureRandom();
        byte[] salt = new byte[SALT_LENGTH];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    /**
     * 生成哈希值
     */
    private static String hasPassword(String password,String salt){
        try {
            MessageDigest digest = MessageDigest.getInstance(PRIVATE_KEY);
            digest.update(Base64.getDecoder().decode(salt));
            byte[] hashedBytes = digest.digest(password.getBytes());
            return Base64.getEncoder().encodeToString(hashedBytes);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 生成带盐的密码哈希
     */
    public static String generatePasswordHash(String password){
        String salt = generateSalt();
        String hashedPassword = hasPassword(password, salt);
        return salt + ":" + hashedPassword;
    }

    /**
     * 验证密码
     */
    public static boolean verifyPassword(String password,String storePassword){
        String[] parts = storePassword.split(":");
        String salt = parts[0];
        String storedHash = parts[1];
        String computedHash = hasPassword(password, salt);
        return storedHash.equals(computedHash);
    }

    public static void main(String[] args) {

    }
}
